package com.bos.service.impl;

import com.bos.dao.repositories.WayBillRepository;
import com.bos.dao.search.WayBillSearchRepository;
import com.bos.domian.base.WayBill;
import com.bos.service.WayBillService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.Map;

/**
 * @author misterWei
 * @create 2018年11月26号:10点25分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Transactional
public class WayBillServiceImpl implements WayBillService {
    @Autowired
    private WayBillRepository wayBillRepository;
    //注入操作搜索数据对象
    @Autowired
    private WayBillSearchRepository wayBillSearchRepository;
    @Override
    public Map<String, Object> pageQuery(Pageable pageable) {
        Page<WayBill> all = wayBillRepository.findAll(pageable);
        Map<String,Object> takeTimeList  = new HashMap<>();
        takeTimeList.put("total",all.getTotalElements());
        takeTimeList.put("rows",all.getContent());
        return takeTimeList;
    }

    @Override
    public void save(WayBill model) {
        WayBill byWayBillNum = wayBillRepository.findByWayBillNum(model.getWayBillNum());

        try {
            if (byWayBillNum!=null && byWayBillNum.getId()!=null) {
                if (byWayBillNum.getSignStatus() != 1){
                    Integer id = byWayBillNum.getId();
                    BeanUtils.copyProperties(byWayBillNum, model);
                    byWayBillNum.setId(id);
                    //更新操作
                    wayBillSearchRepository.save(byWayBillNum);
                }else {
                    throw new RuntimeException("运单不可更改，已经转运！");
                }

            }else{
                //保存到索引库操作
               // BeanUtils.copyProperties(model, byWayBillNum);
                model.setSignStatus(1);
                wayBillRepository.save(model);
                wayBillSearchRepository.save(model);
            }

        } catch (Exception e) {
           e.printStackTrace();
        }
    }
    @Override
    public WayBill findByWayBillNum(String wayBillNum) {
        return wayBillRepository.findByWayBillNum(wayBillNum);
    }
}
